package com.wll.talker.frags.panel;

import android.media.AudioFormat;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.wll.common.app.Application;
import com.wll.common.app.Fragment;
import com.wll.common.tools.AudioPlayHelper;
import com.wll.common.tools.AudioRecordHelper;
import com.wll.common.tools.UiTool;
import com.wll.common.widget.AudioRecordView;
import com.wll.common.widget.GalleryView;
import com.wll.common.widget.recycler.RecyclerAdapter;
import com.wll.face.Face;
import com.wll.factory.Factory;
import com.wll.lame.RecordManager;
import com.wll.lame.recorderlib.RecordConfig;
import com.wll.lame.recorderlib.RecordHelper;
import com.wll.lame.recorderlib.listener.RecordFftDataListener;
import com.wll.lame.recorderlib.listener.RecordResultListener;
import com.wll.lame.recorderlib.listener.RecordSoundSizeListener;
import com.wll.lame.recorderlib.listener.RecordStateListener;
import com.wll.lame.recorderlib.mp3.Mp3Utils;
import com.wll.lame.utils.Logger;
import com.wll.talker.BuildConfig;
import com.wll.talker.R;
import com.wll.talker.activities.MainActivity;
import com.wll.talker.frags.message.ChatFragment;

import net.qiujuer.genius.ui.Ui;

import java.io.File;
import java.util.List;
import java.util.Locale;

/**
 * 底部面板实现
 */
public class PanelFragment extends Fragment {
    private static final String TAG = "PanelFragment";
    private View mFacePanel, mGalleryPanel, mRecordPanel;
    private PanelCallback mCallback;


    public PanelFragment() {
        // Required empty public constructor
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_panel;
    }


    @Override
    protected void initWidget(View root) {
        super.initWidget(root);

        initFace(root);
        initRecord(root);
        initGallery(root);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        doStop();
        initRecordEvent();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
        doStop();
    }

    // 开始初始化方法
    public void setup(PanelCallback callback) {
        mCallback = callback;
    }


    private void initFace(View root) {
        final View facePanel = mFacePanel = root.findViewById(R.id.lay_panel_face);

        View backspace = facePanel.findViewById(R.id.im_backspace);
        backspace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 删除逻辑

                PanelCallback callback = mCallback;
                if (callback == null)
                    return;

                // 模拟一个键盘删除点击
                KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL,
                        0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
                callback.getInputEditText().dispatchKeyEvent(event);
            }
        });

        TabLayout tabLayout = (TabLayout) facePanel.findViewById(R.id.tab);
        ViewPager viewPager = (ViewPager) facePanel.findViewById(R.id.pager);
        tabLayout.setupWithViewPager(viewPager);

        // 每一表情显示48dp
        final int minFaceSize = (int) Ui.dipToPx(getResources(), 48);
        final int totalScreen = UiTool.getScreenWidth(getActivity());
        final int spanCount = totalScreen / minFaceSize;


        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return Face.all(getContext()).size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }


            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                // 添加的
                LayoutInflater inflater = LayoutInflater.from(getContext());
                RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.lay_face_content, container, false);
                recyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount));

                // 设置Adapter
                List<Face.Bean> faces = Face.all(getContext()).get(position).faces;
                FaceAdapter adapter = new FaceAdapter(faces, new RecyclerAdapter.AdapterListenerImpl<Face.Bean>() {
                    @Override
                    public void onItemClick(RecyclerAdapter.ViewHolder holder, Face.Bean bean) {
                        if (mCallback == null)
                            return;
                        // 表情添加到输入框
                        EditText editText = mCallback.getInputEditText();
                        Face.inputFace(getContext(), editText.getText(), bean, (int)
                                (editText.getTextSize() + Ui.dipToPx(getResources(), 2)));

                    }
                });
                recyclerView.setAdapter(adapter);

                // 添加
                container.addView(recyclerView);

                return recyclerView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                // 移除的
                container.removeView((View) object);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                // 拿到表情盘的描述
                return Face.all(getContext()).get(position).name;
            }
        });


    }

    final RecordManager recordManager = RecordManager.getInstance();
    private boolean isStart = false;
    //    private boolean isPause = false;
    private AudioPlayHelper mAudioPlayer;
    String audioPath;

    // 初始化语音
    private void initRecord(View root) {
        View recordView = mRecordPanel = root.findViewById(R.id.lay_panel_record);

        final AudioRecordView audioRecordView = (AudioRecordView) recordView
                .findViewById(R.id.view_audio_record);

        mAudioPlayer = new AudioPlayHelper(null);

        recordManager.init(Factory.app(), BuildConfig.DEBUG);
        recordManager.changeFormat(RecordConfig.RecordFormat.MP3);
//        recordManager.changeRecordConfig(recordManager.getRecordConfig().setSampleRate(16000));
//        recordManager.changeRecordConfig(recordManager.getRecordConfig().setEncodingConfig(AudioFormat.ENCODING_PCM_16BIT));
        String recordDir = Application.getCacheDirFile().getAbsolutePath();
        recordManager.changeRecordDir(recordDir);

//        // 录音的缓存文件
//        File tmpFile = Application.getAudioTmpFile(true);
//        // 录音辅助工具类
//        final AudioRecordHelper helper = new AudioRecordHelper(tmpFile, new AudioRecordHelper.RecordCallback() {
//            @Override
//            public void onRecordStart() {
//                //...
//            }
//
//            @Override
//            public void onProgress(long time) {
//                //...
//            }
//
//            @Override
//            public void onRecordDone(File file, long time) {
//                // 时间是毫秒，小于1秒则不发送
//                if (time < 1000) {
//                    return;
//                }
//
//                // 更改为一个发送的录音文件
//                File audioFile = Application.getAudioTmpFile(false);
//                if (file.renameTo(audioFile)) {
//                    // 通知到聊天界面
//                    PanelCallback panelCallback = mCallback;
//                    if (panelCallback != null) {
//                        panelCallback.onRecordDone(audioFile, time);
//                    }
//                }
//            }
//        });


        // 初始化
        audioRecordView.setup(new AudioRecordView.Callback() {
            @Override
            public void requestStartRecord() {
//                 // 请求开始
//                helper.recordAsync();
                Log.d("开始录音, 文件path：", recordDir);
                doPlay();
            }

            @Override
            public void requestStopRecord(int type) {
                // 请求结束
                switch (type) {
                    case AudioRecordView.END_TYPE_CANCEL:
                    case AudioRecordView.END_TYPE_DELETE:
//                        // 删除和取消都代表想要取消
//                        helper.stop(true);
                        doCancel();
                        if (audioPath != null && !TextUtils.isEmpty(audioPath)) {
                            File file = new File(audioPath);
                            if (file.exists()) {
                                Log.d(TAG, "删除录音文件，路径：" + audioPath);
                                if (file.delete()) {
                                    Log.d(TAG, "文件删除成功");
                                }
                            }
                        }
                        break;
                    case AudioRecordView.END_TYPE_NONE:
                    case AudioRecordView.END_TYPE_PLAY:
//                        // 播放暂时当中就是想要发送
//                        helper.stop(false);
                        doStop();
                        if (audioPath != null && !TextUtils.isEmpty(audioPath))
                            mAudioPlayer.play(audioPath);
                        break;
                }
            }
        });

    }

    private void initRecordEvent() {
        Log.d(TAG, "initRecordEvent");

        recordManager.setRecordStateListener(new RecordStateListener() {
            @Override
            public void onStateChange(RecordHelper.RecordState state) {
                Logger.i(TAG, "RecordState onStateChange %s", state.name());
            }

            @Override
            public void onError(String error) {
                Logger.i(TAG, "RecordState onError %s", error);
            }
        });

        recordManager.setRecordSoundSizeListener(new RecordSoundSizeListener() {
            @Override
            public void onSoundSize(int soundSize) {
                Logger.i(TAG, "声音大小：%s db", soundSize);
            }
        });

        recordManager.setRecordResultListener(new RecordResultListener() {
            @Override
            public void onResult(File result) {
                Logger.i(TAG, "录音文件： " + result.getAbsolutePath());

                audioPath = result.getAbsolutePath();

                if (audioPath != null && !TextUtils.isEmpty(audioPath)) {
                    long time = Mp3Utils.getDuration(audioPath);
                    Logger.i(TAG, "录音文件时长： " + time);

                    if (time < 1000) {
                        return;
                    }

                    // 通知到聊天界面
                    PanelCallback panelCallback = mCallback;
                    if (panelCallback != null) {
                        panelCallback.onRecordDone(result, time);
                    }
                }
            }
        });

//        recordManager.setRecordFftDataListener(new RecordFftDataListener() {
//            @Override
//            public void onFftData(byte[] data) {
//
//            }
//        });
    }

    private void doStop() {
        recordManager.stop();
//        isPause = false;
        isStart = false;
    }

    private void doCancel() {
        recordManager.cancel();
//        isPause = false;
        isStart = false;
    }

    private void doPlay() {
        recordManager.start();
        isStart = true;
//        if (isStart) {
//            recordManager.pause();
//            isPause = true;
//            isStart = false;
//        } else {
//            if (isPause) {
//                recordManager.resume();
//            } else {
//                recordManager.start();
//            }
//            isStart = true;
//        }
    }

    // 初始化图片
    private void initGallery(View root) {
        final View galleryPanel = mGalleryPanel = root.findViewById(R.id.lay_gallery_panel);
        final GalleryView galleryView = (GalleryView) galleryPanel.findViewById(R.id.view_gallery);
        final TextView selectedSize = (TextView) galleryPanel.findViewById(R.id.txt_gallery_select_count);

        galleryView.setup(getLoaderManager(), new GalleryView.SelectedChangeListener() {
            @Override
            public void onSelectedCountChanged(int count) {
                String resStr = getText(R.string.label_gallery_selected_size).toString();
                selectedSize.setText(String.format(resStr, count));
            }
        });

        // 点击事件
        galleryPanel.findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onGalleySendClick(galleryView, selectedSize, galleryView.getSelectedPath());
            }
        });

    }


    // 点击的时候触发，传回一个控件和选中的路径
    private void onGalleySendClick(GalleryView galleryView, TextView selectedSize, String[] paths) {
        // 通知给聊天界面
        // 清理状态
        galleryView.clear();
//        String resStr = getText(R.string.label_gallery_selected_size).toString();
//        selectedSize.setText(String.format(resStr, 0));

        // 删除逻辑
        PanelCallback callback = mCallback;
        if (callback == null)
            return;

        callback.onSendGallery(paths);
    }


    public void showFace() {
        mRecordPanel.setVisibility(View.GONE);
        mGalleryPanel.setVisibility(View.GONE);
        mFacePanel.setVisibility(View.VISIBLE);
    }

    public void showRecord() {
        mRecordPanel.setVisibility(View.VISIBLE);
        mGalleryPanel.setVisibility(View.GONE);
        mFacePanel.setVisibility(View.GONE);
    }

    public void showGallery() {
        mRecordPanel.setVisibility(View.GONE);
        mGalleryPanel.setVisibility(View.VISIBLE);
        mFacePanel.setVisibility(View.GONE);
    }

    // 回调聊天界面的Callback
    public interface PanelCallback {
        EditText getInputEditText();

        // 返回需要发送的图片
        void onSendGallery(String[] paths);

        // 返回录音文件和时常
        void onRecordDone(File file, long time);
    }
}